package com.wing.product.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.device.model.entity.Device;
import com.wing.device.model.response.DeviceVO;
import com.wing.device.service.DeviceService;
import com.wing.product.model.request.ProcessDeviceAddForm;
import com.wing.product.model.response.ProcessDeviceVO;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.ProcessDevice;
import com.wing.product.model.request.ProcessDeviceForm;
import com.wing.product.service.ProcessDeviceService;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-管理", tags = "#/product/processDevice")
@RestController("processDeviceController")
@RequestMapping("product/admin/processDevice")
@RequiredArgsConstructor
public class ProcessDeviceController {

    private final ProcessDeviceService processDeviceService;

    private final DeviceService deviceService;


    @ApiOperation(value = "查询所有", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<ProcessDeviceVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,@RequestParam("processId") Long  processId
    ){

        Page<ProcessDevice> pg = new Page<>(page, limit);
        Map queryParam=new HashMap();
        queryParam.put("sort",StrUtil.toUnderlineCase(sort));
        queryParam.put("order",order);
        queryParam.put("processId",processId);
        IPage<ProcessDeviceVO> list = processDeviceService.pageList4app(pg, queryParam);
        /*List<DeviceVO> deviceList = new ArrayList<>();
        for (ProcessDeviceVO record : list.getRecords()) {
            DeviceVO device = deviceService.getDeviceVO(record.getDeviceCode());
            deviceList.add(device);
        }*/
        return new PageResult<>(list.getRecords(), list.getTotal());
    }
    @GetMapping("/processList")
    public PageResult<DeviceVO> processList(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "desc") String order
            ,@RequestParam("processId") String processId){

        Map queryParam=new HashMap();
        queryParam.put("sort",StrUtil.toUnderlineCase(sort));
        queryParam.put("order",order);
        queryParam.put("processId",processId);

        //List<ProcessDevice> processDevices = processDeviceService.list(new QueryWrapper<ProcessDevice>().eq("process_id", processId));
        List<ProcessDeviceVO> processDevices = processDeviceService.list4app(queryParam);
        List<String> deviceCodes = new ArrayList<>();
        for (ProcessDeviceVO processDevice : processDevices) {
            deviceCodes.add(processDevice.getDeviceCode());
        }
        /*Map queryParam=new HashMap();
        queryParam.put("sort",StrUtil.toUnderlineCase(sort));
        queryParam.put("order",order);
        queryParam.put("process_id",processId);
        Page<DeviceVO> pg = new Page<>(page, limit);
        Page<DeviceVO> deviceVOPage = deviceService.pageList4app(pg, queryParam);*/
        Page<ProcessDevice> pg = new Page<>(page, limit);
        Page<DeviceVO> deviceVOPage = deviceService.pageListProcess(pg, deviceCodes);
        return new PageResult<>(deviceVOPage.getRecords(), deviceVOPage.getTotal());
    }

    @GetMapping("/deviceVOListByProcessId")
    public JsonResult<List<ProcessDeviceVO>> deviceVOListByProcessId(@RequestParam("processId") Long processId){
        Map<String, Object> params = new HashMap<>();
        params.put("processId",processId);
        List<ProcessDeviceVO> processDevices = processDeviceService.list4app(params);
        return JsonResult.success(processDevices);
    }


    @ApiOperation(value = "添加", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(ProcessDeviceForm.Add.class) @RequestBody ProcessDeviceAddForm processDeviceAddForm) {
        int i = 0;
            for (String s : processDeviceAddForm.getDeviceCode()) {
                LambdaQueryWrapper<ProcessDevice> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ProcessDevice :: getProcessId,processDeviceAddForm.getProcessId());
                queryWrapper.eq(ProcessDevice :: getDeviceCode,s);
                ProcessDevice deviceServiceOne = processDeviceService.getOne(queryWrapper);
                if(deviceServiceOne != null){
                    return JsonResult.fail("添加失败:设备编号为：" + s + "已经绑定当前工序！");
                }
                ProcessDeviceForm form = new ProcessDeviceForm();
                form.setDeviceCode(s);
                form.setProcessId(processDeviceAddForm.getProcessId());
                form.setCreatorName(JwtUtils.getLoginNickname());
                i += processDeviceService.add(form);
            }
            if (i > 0) {
                return JsonResult.success("添加成功");
            }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(ProcessDeviceForm.Update.class) ProcessDeviceForm processDeviceForm) {
        ProcessDevice processDevice = processDeviceService.getById(processDeviceForm.getId());
        if(processDevice == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(ProcessDevice.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(processDeviceForm, processDevice, copyOptions);
        if (processDeviceService.updateById(processDevice)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "processDeviceId", value = "id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/delete" )
    public JsonResult delete(Long processDeviceId) {
        if (processDeviceService.removeById(processDeviceId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true, dataType = "Long", paramType = "path")
    })
    @DeleteMapping("/delBatch")
    public JsonResult delBatch(@RequestParam("ids[]") Long[] ids) {
        if (processDeviceService.delBatch(ids) > 0) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }
}
